//APP
if (window.plus) {
    suitePageReady();
} else {
    document.addEventListener('plusready', suitePageReady, false);
}
// Web
$(function() {
    if (AGENT_CLIENT.WEB) {
        suitePageReady();
    }
});
// 初始化方法
function suitePageReady() {
    var _goodsId = getUrlParam("id"); // 15105
    var _currentloginuser = getLocalStorage(STORAGE_MANAGER.user);
    var _suiteGoodsList = [],
        _totalprice = 0,
        _totalcoin = 0,
        _totalgoodscount = 0;
    var suitePage = function() {
        this.init();
    };
    suitePage.prototype = {
        // 初始化
        init: function() {
            this.loaddata();
            this.bindEvent();
        },
        // 绑定事件
        bindEvent: function() {
            var thisPage = this;
            // 返回
            $("#back").on("click", function() {
                back();
            });
            // 选择
            $("#suitecontainer").on("change", "input[name=chbchoose]", function() {
                var status = $(this).prop("checked");
                var index = $(this).attr("tip");
                var price = 0,
                    coin = 0,
                    goodscount = 0;
                if (status) {
                    // 相加
                    price = parseFloat($("#totalprice").text()) + _suiteGoodsList[index].price;
                    coin = parseFloat($("#totalcoin").text()) + _suiteGoodsList[index].coin;
                    goodscount = parseInt($("#goodsCount").text()) + _suiteGoodsList[index].goodscount;
                } else {
                    // 相减
                    price = parseFloat($("#totalprice").text()) - _suiteGoodsList[index].price;
                    coin = parseFloat($("#totalcoin").text()) - _suiteGoodsList[index].coin;
                    goodscount = parseInt($("#goodsCount").text()) - _suiteGoodsList[index].goodscount;
                }
                setTotalPrice(price, coin, goodscount);
                // 取消全选
                var selectedItem = $("input[name='chbchoose']:checked");
                if (selectedItem.length < _suiteGoodsList.length) {
                    $("#checkbox-1-selectAll").prop("checked", false);
                } else {
                    $("#checkbox-1-selectAll").prop("checked", true);
                };
            });
            // 全选
            $("#checkbox-1-selectAll").on("change", function() {
                var status = $(this).prop("checked");
                // 选中所有套件
                $("input[name='chbchoose']").prop("checked", status);
                if (status) {
                    setTotalPrice(_totalprice, _totalcoin, _totalgoodscount);
                } else {
                    setTotalPrice(0, 0, 0);
                }
            });
            // 加入购物车
            $("#btnAddCart").on("click", function() {
                _currentloginuser = getLocalStorage(STORAGE_MANAGER.user);
                if (!_currentloginuser) {
                    redirect("../account/login.html");
                    return;
                }
                var selectedItem = $("input[name='chbchoose']:checked");
                if (selectedItem.length == 0) {
                    $.toast("至少选择一个套装");
                    return;
                }
                $.each(selectedItem, function(i, suiteItem) {
                    var index = $(suiteItem).attr("tip");
                    thisPage.addCart(index);
                });
            });
            // 跳转商品详情
            $("#suitecontainer").on("click", "dl[name=goodsItem]", function() {
                redirect("../goods/goodsdetail.html?id=" + $(this).attr("tip"));
            });

            function setTotalPrice(totalprice, totalcoin, goodscount) {
                $("#totalcoin").text(parseInt(totalcoin));
                $("#totalprice").text(totalprice.toFixed(1));
                $("#goodsCount").text(goodscount);
            }
        },
        // 获取套装数据
        loaddata: function() {
            var thisPage = this;
            $.ajax({
                type: "GET",
                url: CONFIG_MANAGER.RequstUrl + "v1/goods/suite/sku/" + _goodsId,
                beforeSend: function() {
                    $.showWaiting();
                }
            }).done(function(res) {
                if (res && res.length > 0) {
                    thisPage.paintPage(res);
                }
            }).always(function(res) {
                $.closeWaiting();
            });
        },
        // 加载页面
        paintPage: function(suitelist) {
            var html = [];
            $.each(suitelist, function(i, suiteItem) {
                var goodslist = suiteItem.sku_item;
                var tempprice = 0,
                    tempcoin = 0;
                $.each(goodslist, function(j, goodsitem) {
                    tempprice = tempprice + parseFloat(goodsitem.shop_price);
                    tempcoin = tempcoin + parseFloat(goodsitem.coin);
                });
                _totalprice = _totalprice + tempprice;
                _totalcoin = _totalcoin + tempcoin;
                _totalgoodscount = _totalgoodscount + goodslist.length;
                _suiteGoodsList.push({
                    suiteno: suiteItem.suiteNo,
                    goodscount: goodslist.length,
                    price: tempprice,
                    coin: tempcoin
                });
                html.push("<div class='mbtopbottom sqshbg' name='suiteItem'><div class='with100 overflow'>");
                html.push("<div class='shop-title mbbottom'><div class='item'><div class='shop-title-content'><span class='shop-title-name'>");
                html.push("<b class='checkboxFour'><input type='checkbox' id='checkbox-1-" + i + "' tip='" + i + "' tip='" + i + "'  name='chbchoose'  class='checkbox-gx'>");
                html.push("<label for= 'checkbox-1-" + i + "' ></label></b><label for= 'checkbox-1-" + i + "' >套装" + (i + 1) + "</label></span>");
                var coinTemplate = (tempcoin > 0) ? "+<span class='suite-coin hover'><b><img src='../../images/jbtub.jpg'></b>" + tempcoin + "</span>" : "";
                html.push("<div class='shop-title-detail'><span id='coupons_0' style='display:inline-block;text-align:center;'>套装价格：<span class='hongzei'>￥" + tempprice + "</span>" + coinTemplate + "</b></span>");
                html.push("</div></div></div></div>");
                $.each(goodslist, function(j, goodsitem) {
                    html.push("<dl class='cpxqxztop cpxqxztop1 mtop0 overflow mbbottom' name='goodsItem' tip='" + goodsitem.sku_id + "'>");
                    html.push("<dt><img src='" + getImageUrl(goodsitem.logo, 350, 350) + "' /></dt><dd>" + goodsitem.sku_name + "</dd>");
                    coinTemplate = (goodsitem.coin > 0) ? "+<span class='suite-coin hover'><b><img src='../../images/jbtub.jpg'></b>" + goodsitem.coin + "</span>" : "";
                    html.push("<dd class='wlxxlc wlxxlc5 floatr mleft0'><span class='hongzei'>￥" + goodsitem.shop_price + "</span>" + coinTemplate + "</dd></dl>");
                });
                html.push("</div></div>");
            });
            $("#suitecontainer").html(html.join(""));
            if (_totalcoin > 0) {
                $("#totalcoinspan").show();
            }
            if (_suiteGoodsList.length > 0) {
                $("input[name='chbchoose']:first").click();
            }
        },
        // 加入购物车
        addCart: function(index) {
            var suiteItem = _suiteGoodsList[index];
            var postdata = {
                suite_no: suiteItem.suiteno,
                member_id: _currentloginuser.id,
                session_id: getSessionID(),
                qty: suiteItem.goodscount,
                org_id: CONFIG_MANAGER.orgId,
            };
            $.ajax({
                type: "POST",
                url: CONFIG_MANAGER.RequstUrl + "v1/cart/add/suite",
                data: JSON.stringify(postdata),
                contentType: 'application/json',
                headers: {
                    token: _currentloginuser.token
                },
                beforeSend: function() {
                    $.showWaiting();
                }
            }).done(function(res) {
              //加入购物车之后重新计算商品个数
              $.ajax({
                  type: "GET",
                  headers: {token: _currentloginuser.token},
                  url: CONFIG_MANAGER.RequstUrl + "v1/cart/sum/" + _currentloginuser.id,
                  async: true,
              }).done(function (data) {
                setLocalStorage(STORAGE_MANAGER.cacheproductcount, data.count);
                if (AGENT_CLIENT.APP) {
                  plus.webview.getWebviewById("../home/main.html").evalJS("getShopcartProductCount()");
                  plus.webview.getWebviewById("../home/main.html").evalJS("redirectTab(4)");
                }else{
                	redirect("../shopcart/shoppingcart.html");
                }
              }).always(function (data) {
                  $.closeWaiting();
              });                
                
            }).always(function(data) {
                $.closeWaiting();
            });
        }
    };
    var _suitePage = new suitePage();
}